import 'dart:convert';
import 'package:http/http.dart' as http;
import '../services/moment_service.dart';
import 'token_manager.dart';

class HttpClient {
  // 请求拦截器 - 添加Authorization头
  static Future<Map<String, String>> _getHeaders() async {
    final headers = <String, String>{
      'Content-Type': 'application/json',
    };

    // 获取token并添加到请求头
    final token = await TokenManager.getToken();
    if (token != null && token.isNotEmpty) {
      headers['Authorization'] = 'Bearer $token';
    }

    return headers;
  }

  // 响应拦截器 - 处理401
  static void _handleResponse(http.Response response, Function()? onUnauthorized) {
    if (response.statusCode == 401) {
      // 清除token
      TokenManager.clearUser();
      // 触发未授权回调（跳转到登录页）
      onUnauthorized?.call();
    }
  }

  // GET请求
  static Future<http.Response> get(
    String path, {
    Map<String, String>? queryParams,
    Function()? onUnauthorized,
  }) async {
    final headers = await _getHeaders();
    final url = Uri.parse('${MomentService.baseUrl}$path')
        .replace(queryParameters: queryParams);

    print('=== HTTP GET ===');
    print('URL: $url');
    print('Headers: $headers');

    final response = await http.get(url, headers: headers);

    print('Status Code: ${response.statusCode}');
    print('Response Body: ${utf8.decode(response.bodyBytes)}');

    _handleResponse(response, onUnauthorized);
    return response;
  }

  // POST请求
  static Future<http.Response> post(
    String path, {
    Map<String, dynamic>? body,
    Function()? onUnauthorized,
  }) async {
    final headers = await _getHeaders();
    final url = Uri.parse('${MomentService.baseUrl}$path');

    print('=== HTTP POST ===');
    print('URL: $url');
    print('Headers: $headers');
    print('Body: ${body != null ? json.encode(body) : 'null'}');

    final response = await http.post(
      url,
      headers: headers,
      body: body != null ? json.encode(body) : null,
    );

    print('Status Code: ${response.statusCode}');
    print('Response Body: ${utf8.decode(response.bodyBytes)}');

    _handleResponse(response, onUnauthorized);
    return response;
  }

  // PUT请求
  static Future<http.Response> put(
    String path, {
    Map<String, dynamic>? body,
    Function()? onUnauthorized,
  }) async {
    final headers = await _getHeaders();
    final url = Uri.parse('${MomentService.baseUrl}$path');

    print('=== HTTP PUT ===');
    print('URL: $url');
    print('Headers: $headers');
    print('Body: ${body != null ? json.encode(body) : 'null'}');

    final response = await http.put(
      url,
      headers: headers,
      body: body != null ? json.encode(body) : null,
    );

    print('Status Code: ${response.statusCode}');
    print('Response Body: ${utf8.decode(response.bodyBytes)}');

    _handleResponse(response, onUnauthorized);
    return response;
  }

  // DELETE请求
  static Future<http.Response> delete(
    String path, {
    Function()? onUnauthorized,
  }) async {
    final headers = await _getHeaders();
    final url = Uri.parse('${MomentService.baseUrl}$path');

    print('=== HTTP DELETE ===');
    print('URL: $url');
    print('Headers: $headers');

    final response = await http.delete(url, headers: headers);

    print('Status Code: ${response.statusCode}');
    print('Response Body: ${utf8.decode(response.bodyBytes)}');

    _handleResponse(response, onUnauthorized);
    return response;
  }
}
